package net.chrone.quickpayapi.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.chrone.quickpayapi.mapper.MccMapper;
import net.chrone.quickpayapi.model.Mcc;
import net.chrone.quickpayapi.service.MccService;
import net.chrone.quickpayapi.service.SeqService;

@Service
public class MccServiceImpl implements MccService {

	@Autowired
	private MccMapper mccMapper;
	@Autowired
	private SeqService seqService;

	@Transactional
	@Override
	public String getMerchantId() {
		synchronized (this) {
			Mcc mcc = mccMapper.getMccUsing();//加锁
			if (mcc != null) {// 使用中
				if (mcc.getNum() >= 9999) {
					mcc.setIsUse(2);// 2已使用
					mccMapper.updateByPrimaryKey(mcc);
					mcc = null;
				}
			}
			if (mcc == null) {
				mcc = mccMapper.getMccNotUseFirst();
			}
			if (mcc == null) {
				return null;
			}
			mcc.setIsUse(1);
			mcc.setNum(mcc.getNum() + 1);
			mccMapper.updateByPrimaryKey(mcc);
			String merchantId = "9291101" + mcc.getMcc() + seqService.format(mcc.getNum(), 4);
			System.out.println("=========="+merchantId);
			return merchantId;
		}
	}
}
